import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../database/prisma.service';

/**
 * JWT策略
 * 零隐患MFIS规范 - 解决隐患：#15 密钥管理
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly prisma: PrismaService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_SECRET'),
      issuer: 'uc-system',
      audience: 'uc-system-client',
    });
  }

  async validate(payload: any) {
    try {
      // 验证用户是否仍然存在且活跃
      const user = await this.prisma.doctor.findFirst({
        where: {
          doctor_id: payload.sub,
          is_active: true,
          deleted_at: null,
        },
        select: {
          doctor_id: true,
          username: true,
          email: true,
          role: true,
          is_active: true,
        },
      });

      if (!user) {
        throw new UnauthorizedException('用户不存在或已被禁用');
      }

      // 检查账户是否被锁定
      if (user.locked_until && user.locked_until > new Date()) {
        throw new UnauthorizedException('账户已被锁定');
      }

      return {
        doctor_id: user.doctor_id,
        username: user.username,
        email: user.email,
        role: user.role,
        is_active: user.is_active,
      };
    } catch (error) {
      if (error instanceof UnauthorizedException) {
        throw error;
      }

      throw new UnauthorizedException('令牌验证失败');
    }
  }
}